﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlServerCe;

namespace CEQuery
{
    public partial class ValidateDB : Form
    {
        public string ConnectionString { get; set; }

        public ValidateDB()
        {
            InitializeComponent();
        }

        private void ValidateDB_Load(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(ConnectionString))
                {
                    using (SqlCeConnection localConnection = new SqlCeConnection(ConnectionString))
                    {
                        using (SqlCeEngine engine = new SqlCeEngine(ConnectionString))
                        {
                            if (engine.Verify(VerifyOption.Default))
                            {
                                lblValidateMsg.Text = "DB has been verified. No corruption has been detected.";
                                grpRepair.Enabled = false;
                            }
                            else
                            {
                                lblValidateMsg.Text = "Corruption has been detected. Please Repair with the following option.";
                                grpRepair.Enabled = false;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnRepair_Click(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(ConnectionString))
                {
                    using (SqlCeConnection localConnection = new SqlCeConnection(ConnectionString))
                    {
                        using (SqlCeEngine engine = new SqlCeEngine(ConnectionString))
                        {
                            if (rdbDeleteCorruptedRows.Checked)
                                engine.Repair(ConnectionString, RepairOption.DeleteCorruptedRows);
                            if (rdbRecoverAllOrFail.Checked)
                                engine.Repair(ConnectionString, RepairOption.RecoverAllOrFail);
                            if (rdbRecoverAllPossibleRows.Checked)
                                engine.Repair(ConnectionString, RepairOption.RecoverAllPossibleRows);

                            MessageBox.Show("DB has been Repaired Successfully. Please reload the DB.");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
